package com.wanshu.common.aspect;

import com.alibaba.fastjson.JSON;
import com.wanshu.common.annotation.SystemLog;
import com.wanshu.sys.entity.SysLog;
import com.wanshu.sys.service.ISysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@EnableAspectJAutoProxy
public class SysLogAspect {

    @Autowired
    private ISysLogService sysLogService;

    @Pointcut("@annotation(com.wanshu.common.annotation.SystemLog)")
    public void logPointcut(){

    }

    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint point){
        Object obj = null;
        try {
            System.out.println("处理前......");
            long startTime = System.currentTimeMillis();
            obj = point.proceed();
            long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            saveSysLog(point, time);
            System.out.println("处理后......");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }

    private void saveSysLog(ProceedingJoinPoint point, long time){
        SysLog sysLog = new SysLog();
        //存入当前用户
        //获取当前调用的方法
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        String classpath = point.getTarget().getClass().getName();
        sysLog.setMethod(classpath + "." + method.getName() + "()");

        //获取方法 @SysLog 注解的描述信息
        SystemLog systemLogAnno = method.getAnnotation(SystemLog.class);
        if(systemLogAnno != null){
            sysLog.setOperation(systemLogAnno.value());
        }

        //获取方法的参数
        Object[] paramArgs = point.getArgs();
        String params = JSON.toJSON(paramArgs).toString();
        sysLog.setParams(params);

        //方法调用时长
        sysLog.setTime(time);
        //创建时间
        sysLog.setCreateDate(LocalDateTime.now());

        sysLogService.save(sysLog);

    }

}
